import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;



@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf8");
        resp.setCharacterEncoding("utf8");
        //1.获取请求中的参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        //2.和数据库中的内容比较
        UserDao userDao = new UserDao();
        User user = userDao.findByUsernameAndPassword(username,password);


        //如果用户名没有在数据库中
        if(user == null){
            resp.setContentType("text/html; charset = utf8");
            resp.getWriter().write("当前用户名或密码错误");
            resp.sendRedirect("login.html");
            return;
        }
        //如果用户名在数据库，但密码不正确
        if (!user.getPassword().equals(password)){
            //改这个用户名登录错误的次数 failcount
            userDao.updateState(username,user.getFailcount());
            resp.setContentType("text/html; charset = utf8");
            resp.getWriter().write("当前用户名或密码错误");
            resp.sendRedirect("login.html");
            return;
        }


        //3.如果在数据库中，则跳转到main页面
        resp.sendRedirect("main.html");


    }
}
